package com.lifesea.notify.mq.handler;

import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyContext;
import com.alibaba.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus;
import com.alibaba.rocketmq.common.message.MessageExt;
import com.lifesea.base.entity.SmsRequest;
import com.lifesea.base.entity.SmsSendResult;
import com.lifesea.commons.exception.ErrorCodeConst;
import com.lifesea.commons.exception.ErrorCodeException;
import com.lifesea.notify.sms.ISmsService;
import com.lifesea.notify.sms.SmsServiceRegister;
import com.lifesea.notify.sms.ZgjkwSmsSender;
import com.lifesea.notify.utils.RandomUtils;
import com.lifesea.rocketmq.utils.handler.MessageHandler;
import com.lifesea.rocketmq.utils.message.MessageDecoder;
import com.lifesea.rocketmq.utils.message.codec.JsonMessageDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.Set;

/**
 * Push消息处理器
 */
@Component
public class SmsHandler implements MessageHandler<SmsRequest> {

    private static final Logger logger = LoggerFactory.getLogger(SmsHandler.class);

    @Autowired
    private ZgjkwSmsSender smsService;

    /**
     * 注册短信发送通道
     */
    @PostConstruct
    public void register() {
        smsService.register();
    }

    @Override
    public ConsumeConcurrentlyStatus process(SmsRequest request, MessageExt message, ConsumeConcurrentlyContext context) {
        logger.info("[SMS SEND]接收,msgId={},request={}", message.getMsgId(), request);

        // 判断接收号码是否为空
        if (request.getMobiles() == null || request.getMobiles().length == 0) {
            logger.error("忽略请求,接收号码为空");
            return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
        }

        for (String mobile : request.getMobiles()) {
            ISmsService sender = getSender(mobile.substring(0, 3));
            SmsSendResult result = sender.sending(mobile, request.getText(), request.getModel());
            logger.info("SmsSendResult={}", result);
        }

        return ConsumeConcurrentlyStatus.CONSUME_SUCCESS;
    }

    public ISmsService getSender(String key) {
        Set<ISmsService> set = SmsServiceRegister.senders.get(key);

        if (set == null) {
            set = SmsServiceRegister.senders.get("*");
        }

        if (set == null) {
            throw new ErrorCodeException(ErrorCodeConst.GLOBAL_REQCHK_ERROR, "未配置默认的短信通道");
        }

        return RandomUtils.getRandomElement(set);

    }

    @Override
    public MessageDecoder<SmsRequest> getMessageDecoder() {
        return new JsonMessageDecoder<>(SmsRequest.class);
    }

}



